<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车辆名称" prop="carName">
        <el-input
          v-model="queryParams.carName"
          placeholder="请输入车辆名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车牌号" prop="carPlateNumber">
        <el-input
          v-model="queryParams.carPlateNumber"
          placeholder="请输入车牌号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="租出状态" prop="carRentalStatus">
        <el-select v-model="queryParams.carRentalStatus" placeholder="请选择租出状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.car_rental_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnabled">
        <el-select v-model="queryParams.isEnabled" placeholder="请选择是否启用" clearable size="small">
          <el-option
            v-for="dict in dict.type.car_enable_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['cms:car:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['cms:car:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['cms:car:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['cms:car:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getPage"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="carList" @selection-change="handleSelectionChange" :fit="true">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="55" align="center" fixed/>
      <el-table-column label="车辆名称" align="left" prop="carName" width="160" fixed/>
      <el-table-column label="车辆图片" align="center" prop="carImageUrl" width="100" fixed>
        <template slot-scope="scope">
          <image-preview :src="scope.row.carImageUrl"/>
        </template>
      </el-table-column>
      <el-table-column label="车牌号" align="center" prop="carPlateNumber" fit fixed width="120px">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.carPlateNumber.substring(2).length ==6"
          >{{ scope.row.carPlateNumber.substring(0, 2) }} ● {{ scope.row.carPlateNumber.substring(2) }}
          </el-tag>
          <el-tag v-if="scope.row.carPlateNumber.substring(2).length ==5"
          >{{ scope.row.carPlateNumber.substring(0, 2) }} ● {{ scope.row.carPlateNumber.substring(2) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="车辆品牌" align="center" prop="carBrand"/>
      <el-table-column label="车辆型号" align="center" prop="carModel"/>
      <el-table-column label="车辆能源类型" align="center" prop="carEnergyType"/>
      <el-table-column label="车辆排量" align="center" prop="carDisplacement"/>
      <el-table-column label="变速箱类型" align="center" prop="carGearboxType"/>
      <el-table-column label="车辆级别" align="center" prop="carSizeLevel"/>
      <el-table-column label="车身结构" align="center" prop="carBodyStructure"/>
      <el-table-column label="车辆座位数" align="center" prop="carSeatNumber"/>
      <el-table-column label="上市时间" align="center" prop="carMarketTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.carMarketTime, '{y}-{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="车辆里程" align="center" prop="carMileage">
        <template slot-scope="scope">
          <span>{{scope.row.carMileage + ' km'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="租出状态" align="center" prop="carRentalStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.car_rental_status" :value="scope.row.carRentalStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="租赁地址" align="left" prop="storeAddress" width="250px"/>
      <el-table-column label="租金" align="center" prop="rentalPrice"/>
      <el-table-column label="押金" align="center" prop="depositPrice"/>
      <el-table-column label="是否启用" align="center" prop="isEnabled">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.car_enable_status" :value="scope.row.isEnabled"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="info"
            icon="el-icon-thumb"
            @click="handleDetail(scope.row)"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['cms:car:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['cms:car:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="pagination.total>0"
      :total="pagination.total"
      :page.sync="pagination.current"
      :limit.sync="pagination.size"
      @pagination="getPage"
    />

    <!-- 添加或修改车辆信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属门店" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请输入车辆所属门店" filterable size="medium">
            <el-option
              v-for="store in storeList"
              :key="store.storeId"
              :label="store.storeName"
              :value="store.storeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车辆名称" prop="carName">
          <el-input v-model="form.carName" placeholder="请输入车辆名称"/>
        </el-form-item>
        <el-form-item label="车辆品牌" prop="carBrand">
          <el-input v-model="form.carBrand" placeholder="请输入车辆品牌"/>
        </el-form-item>
        <el-form-item label="车辆型号" prop="carModel">
          <el-input v-model="form.carModel" placeholder="请输入车辆型号"/>
        </el-form-item>
        <el-form-item label="车牌号" prop="carPlateNumber">
          <el-input v-model="form.carPlateNumber" placeholder="请输入车牌号"/>
        </el-form-item>
        <el-form-item label="车辆图片">
          <image-upload v-model="form.carImageUrl"/>
        </el-form-item>
        <el-form-item label="租金" prop="rentalPrice">
          <el-input v-model="form.rentalPrice" placeholder="请输入租金"/>
        </el-form-item>
        <el-form-item label="押金" prop="depositPrice">
          <el-input v-model="form.depositPrice" placeholder="请输入押金"/>
        </el-form-item>
        <el-form-item label="车辆排量" prop="carDisplacement">
          <el-input v-model="form.carDisplacement" placeholder="请输入车辆排量"/>
        </el-form-item>
        <el-form-item label="车架号" prop="carVin">
          <el-input v-model="form.carVin" placeholder="请输入车架号"/>
        </el-form-item>
        <el-form-item label="车辆级别" prop="carSizeLevel">
          <el-input v-model="form.carSizeLevel" placeholder="请输入车辆级别"/>
        </el-form-item>
        <el-form-item label="车身结构" prop="carBodyStructure">
          <el-input v-model="form.carBodyStructure" placeholder="请输入车身结构"/>
        </el-form-item>
        <el-form-item label="车辆座位数" prop="carSeatNumber">
          <el-input v-model="form.carSeatNumber" placeholder="请输入车辆座位数"/>
        </el-form-item>
        <el-form-item label="油箱容积" prop="carTankCapacity">
          <el-input v-model="form.carTankCapacity" placeholder="请输入油箱容积"/>
        </el-form-item>
        <el-form-item label="上市时间" prop="carMarketTime">
          <el-date-picker clearable size="small"
                          v-model="form.carMarketTime"
                          type="datetime"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择上市时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="出厂时间" prop="carManufactureTime">
          <el-date-picker clearable size="small"
                          v-model="form.carManufactureTime"
                          type="datetime"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择出厂时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车辆里程" prop="carMileage">
          <el-input v-model="form.carMileage" placeholder="请输入车辆里程"/>
        </el-form-item>
        <el-form-item label="租出状态" prop="carRentalStatus">
          <el-select v-model="form.carRentalStatus" placeholder="请选择租出状态">
            <el-option
              v-for="dict in dict.type.car_rental_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="isEnabled">
          <el-select v-model="form.isEnabled" placeholder="请选择是否启用">
            <el-option
              v-for="dict in dict.type.car_enable_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--车辆详情信息框-->
    <Detail ref="detail"/>
  </div>
</template>

<script>
import { listCar, getCar, delCar, addCar, updateCar, pageCar } from '@/api/cms/car'
import { listStore } from '@/api/pms/store'
import Detail from '@/views/cms/car/Detail'

export default {
  name: 'Car',
  components: { Detail },
  dicts: ['car_enable_status', 'car_rental_status'],
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车辆信息表格数据
      carList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      //门店列表
      storeList:[],
      // 查询参数,
      searchParams: {
        queryParams: []
      },
      pagination: {
        current: 1, // 当前页
        size: 10, // 每页显示多少条
        total: 1 // 总数
      },
      queryParams: {
        carName: undefined,
        carPlateNumber: undefined,
        carRentalStatus: undefined,
        isEnabled: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        storeId: [
          { required: true, message: '所属门店id不能为空', trigger: 'blur' }
        ],
        carName: [
          { required: true, message: '车辆名称不能为空', trigger: 'blur' }
        ],
        carBrand: [
          { required: true, message: '车辆品牌不能为空', trigger: 'blur' }
        ],
        carModel: [
          { required: true, message: '车辆型号不能为空', trigger: 'blur' }
        ],
        carEnergyType: [
          { required: true, message: '车辆能源类型不能为空', trigger: 'change' }
        ],
        carDisplacement: [
          { required: true, message: '车辆排量不能为空', trigger: 'blur' }
        ],
        carPlateNumber: [
          { required: true, message: '车牌号不能为空', trigger: 'blur' }
        ],
        carVin: [
          { required: true, message: '车架号不能为空', trigger: 'blur' }
        ],
        carGearboxType: [
          { required: true, message: '变速箱类型不能为空', trigger: 'change' }
        ],
        carSizeLevel: [
          { required: true, message: '车辆级别不能为空', trigger: 'blur' }
        ],
        carBodyStructure: [
          { required: true, message: '车身结构不能为空', trigger: 'blur' }
        ],
        carSeatNumber: [
          { required: true, message: '车辆座位数不能为空', trigger: 'blur' }
        ],
        carTankCapacity: [
          { required: true, message: '油箱容积不能为空', trigger: 'blur' }
        ],
        carMarketTime: [
          { required: true, message: '上市时间不能为空', trigger: 'blur' }
        ],
        carManufactureTime: [
          { required: true, message: '出厂时间不能为空', trigger: 'blur' }
        ],
        carImageUrl: [
          { required: true, message: '车辆图片不能为空', trigger: 'blur' }
        ],
        carMileage: [
          { required: true, message: '车辆里程不能为空', trigger: 'blur' }
        ],
        carRentalStatus: [
          { required: true, message: '租出状态不能为空', trigger: 'change' }
        ],
        rentalPrice: [
          { required: true, message: '租金不能为空', trigger: 'blur' }
        ],
        depositPrice: [
          { required: true, message: '押金不能为空', trigger: 'blur' }
        ],
        isEnabled: [
          { required: true, message: '是否启用不能为空', trigger: 'change' }
        ]
      },
      carId: ''
    }
  },
  created() {
    this.getPage()
  },
  methods: {
    /** 查询车辆信息列表 */
    getList() {
      this.loading = true
      pageCar(this.queryParams).then(response => {
        this.carList = response.data.list
        this.total = response.data.total
        this.loading = false
      })
    },
    getPage() {
      this.loading = true
      const params = Object.assign({}, this.pagination, { queryParams: JSON.stringify(this.searchParams.queryParams) })
      pageCar(params).then(response => {
        this.carList = response.data.list
        this.pagination.total = response.data.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        carId: undefined,
        storeId: undefined,
        carName: undefined,
        carBrand: undefined,
        carModel: undefined,
        carEnergyType: undefined,
        carDisplacement: undefined,
        carPlateNumber: undefined,
        carVin: undefined,
        carGearboxType: undefined,
        carSizeLevel: undefined,
        carBodyStructure: undefined,
        carSeatNumber: undefined,
        carTankCapacity: undefined,
        carMarketTime: undefined,
        carManufactureTime: undefined,
        carImageUrl: undefined,
        carMileage: undefined,
        carRentalStatus: undefined,
        rentalPrice: undefined,
        depositPrice: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        deletedId: undefined,
        deletedTime: undefined,
        isDeleted: undefined,
        isEnabled: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pagination.current = 1
      this.searchParams.queryParams = []
      console.log('items', this.queryParams)
      const queryParams = this.queryParams
      for (let key in queryParams) {
        console.log('key', queryParams[key])
        if (queryParams[key] !== undefined) {
          this.searchParams.queryParams.push({
            'columnName': key,
            'selectCondition': 'like',
            'val': [queryParams[key]]
          })
        }
      }
      this.getPage()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.carId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const carId = row.carId || this.ids
      this.$nextTick(() => {
        this.$refs.detail.getCarInfo(true, carId)
      })
    },
    handleAdd() {
      this.reset()
      this.getStoreList()
      this.open = true
      this.title = '添加车辆信息'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true
      this.reset()
      const carId = row.carId || this.ids
      this.getStoreList()
      getCar(carId).then(response => {
        this.loading = false
        this.form = response.data
        this.open = true
        this.title = '修改车辆信息'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.buttonLoading = true
          if (this.form.carId != null) {
            updateCar(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getPage()
            }).finally(() => {
              this.buttonLoading = false
            })
          } else {
            addCar(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getPage()
            }).finally(() => {
              this.buttonLoading = false
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const carIds = row.carId || this.ids
      this.$modal.confirm('是否确认删除车辆信息编号为"' + carIds + '"的数据项？').then(() => {
        this.loading = true
        return delCar(carIds)
      }).then(() => {
        this.loading = false
        this.getPage()
        this.$modal.msgSuccess('删除成功')
      }).finally(() => {
        this.loading = false
      })
    },
    getStoreList(){
      listStore().then((res)=>{
        this.storeList=res.data
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cms/car/export', {
        ...this.queryParams
      }, `car_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
